import { create } from 'zustand';

const mockCoupons = [
  {
    id: 1,
    slug: 'new-user-discount',
    name: '新用户专享优惠',
    discountRate: 20,
    validDays: 30,
    status: 'active',
    createdAt: '2024-03-15 10:00:00',
    updatedAt: '2024-03-15 10:00:00'
  },
  {
    id: 2,
    slug: 'weekend-special',
    name: '周末特惠券',
    discountRate: 15,
    validDays: 7,
    status: 'active',
    createdAt: '2024-03-14 09:00:00',
    updatedAt: '2024-03-14 09:00:00'
  },
  {
    id: 3,
    slug: 'birthday-gift',
    name: '生日礼品券',
    discountRate: 30,
    validDays: 14,
    status: 'active',
    createdAt: '2024-03-13 14:00:00',
    updatedAt: '2024-03-13 14:00:00'
  },
  {
    id: 4,
    slug: 'vip-exclusive',
    name: 'VIP会员专属',
    discountRate: 25,
    validDays: 60,
    status: 'inactive',
    createdAt: '2024-03-12 11:00:00',
    updatedAt: '2024-03-12 11:00:00'
  },
  {
    id: 5,
    slug: 'flash-sale',
    name: '限时抢购券',
    discountRate: 10,
    validDays: 3,
    status: 'active',
    createdAt: '2024-03-10 10:00:00',
    updatedAt: '2024-03-10 10:00:00'
  },
  {
    id: 6,
    slug: 'holiday-special',
    name: '节日特别优惠',
    discountRate: 35,
    validDays: 21,
    status: 'inactive',
    createdAt: '2024-03-08 09:00:00',
    updatedAt: '2024-03-08 09:00:00'
  },
  {
    id: 7,
    slug: 'referral-reward',
    name: '推荐奖励券',
    discountRate: 18,
    validDays: 45,
    status: 'active',
    createdAt: '2024-03-07 15:00:00',
    updatedAt: '2024-03-07 15:00:00'
  },
  {
    id: 8,
    slug: 'summer-cool',
    name: '夏日清凉券',
    discountRate: 22,
    validDays: 90,
    status: 'active',
    createdAt: '2024-03-06 12:00:00',
    updatedAt: '2024-03-06 12:00:00'
  }
];

const useCouponsStore = create((set, get) => ({
  // 状态
  coupons: [],
  loading: false,
  filters: {
    status: 'all',
    searchText: ''
  },

  // 获取优惠券列表
  getCoupons: async (filters = {}) => {
    set({ loading: true });
    
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      let filtered = [...mockCoupons];
      
      // 应用筛选
      if (filters.status && filters.status !== 'all') {
        filtered = filtered.filter(c => c.status === filters.status);
      }
      
      if (filters.searchText) {
        const searchLower = filters.searchText.toLowerCase();
        filtered = filtered.filter(c =>
          c.name.toLowerCase().includes(searchLower) ||
          c.slug.toLowerCase().includes(searchLower)
        );
      }
      
      // 按ID倒序排序（最新的在前）
      filtered.sort((a, b) => b.id - a.id);
      
      set({ 
        coupons: filtered,
        filters: { ...get().filters, ...filters },
        loading: false 
      });
      
      return filtered;
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  },

  // 创建优惠券
  createCoupon: async (coupon) => {
    set({ loading: true });
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const newCoupon = {
        ...coupon,
        id: Date.now(),
        createdAt: new Date().toLocaleString(),
        updatedAt: new Date().toLocaleString()
      };
      
      mockCoupons.push(newCoupon);
      await get().getCoupons(get().filters);
      
      return newCoupon;
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  },

  // 更新优惠券
  updateCoupon: async (id, updates) => {
    set({ loading: true });
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const index = mockCoupons.findIndex(c => c.id === id);
      if (index !== -1) {
        mockCoupons[index] = {
          ...mockCoupons[index],
          ...updates,
          updatedAt: new Date().toLocaleString()
        };
      }
      
      await get().getCoupons(get().filters);
      return mockCoupons[index];
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  },

  // 删除优惠券
  deleteCoupon: async (id) => {
    set({ loading: true });
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const index = mockCoupons.findIndex(c => c.id === id);
      if (index !== -1) {
        mockCoupons.splice(index, 1);
      }
      
      await get().getCoupons(get().filters);
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  },

  // 切换优惠券状态
  toggleCouponStatus: async (id, status) => {
    return await get().updateCoupon(id, { status });
  },

  // 设置筛选条件
  setFilters: (filters) => {
    set({ filters: { ...get().filters, ...filters } });
    get().getCoupons({ ...get().filters, ...filters });
  },

  // 清空筛选条件
  clearFilters: () => {
    const defaultFilters = {
      status: 'all',
      searchText: ''
    };
    set({ filters: defaultFilters });
    get().getCoupons(defaultFilters);
  }
}));

export default useCouponsStore;